import { get, post, del } from './base'
import type { ApiResponse, PaginatedResponse } from './base'
import type { Conversation, Message, ProcessingTask, ResultPanel } from '../types/home'

// 对话相关接口
export interface GetConversationsParams {
  page?: number
  pageSize?: number
  type?: 'knowledge' | 'data' | 'image' | 'code'
  search?: string
}

export interface CreateConversationRequest {
  title: string
  type: 'knowledge' | 'data' | 'image' | 'code'
  initial_message?: string
}

export interface ConversationDetail {
  id: number
  title: string
  created_at: string
  type: 'knowledge' | 'data' | 'image' | 'code'
  messages: Message[]
  processing_tasks: ProcessingTask[]
  result_panels: ResultPanel[]
}

// 获取对话列表
export async function getConversations(params?: GetConversationsParams): Promise<Conversation[]> {
  try {
    // 如果有真实API，使用真实API
    // const response = await get<PaginatedResponse<Conversation>>('/conversations', params)
    // return response.data.items
    
    // 模拟数据，后续替换为真实API
    return [
      { 
        id: 1, 
        title: '深圳监测站分析方法', 
        created_at: new Date(Date.now() - 86400000).toISOString(), 
        type: 'knowledge' as const 
      },
      { 
        id: 2, 
        title: '深圳AQI趋势分析', 
        created_at: new Date(Date.now() - 172800000).toISOString(), 
        type: 'data' as const 
      },
      { 
        id: 3, 
        title: '臭氧变化趋势图分析', 
        created_at: new Date(Date.now() - 259200000).toISOString(), 
        type: 'image' as const 
      },
      { 
        id: 4, 
        title: 'Python代码性能分析', 
        created_at: new Date(Date.now() - 345600000).toISOString(), 
        type: 'code' as const 
      }
    ]
  } catch (error) {
    console.error('Failed to get conversations:', error)
    throw error
  }
}

// 获取对话详情
export async function getConversationDetail(id: number): Promise<ConversationDetail> {
  try {
    // 如果有真实API，使用真实API
    // const response = await get<ConversationDetail>(`/conversations/${id}`)
    // return response.data
    
    // 模拟数据，后续替换为真实API
    // 这里会根据不同的id返回不同的模拟数据
    const mockData: Record<number, ConversationDetail> = {
      1: {
        id: 1,
        title: '深圳监测站分析方法',
        created_at: new Date(Date.now() - 86400000).toISOString(),
        type: 'knowledge',
        messages: [
          {
            id: 1,
            role: 'user',
            content: '你好，请介绍一下Vue3的主要特性',
            created_at: new Date('2024-01-15T10:30:00').toISOString()
          },
          {
            id: 2,
            role: 'assistant',
            content: 'Vue3是一个现代化的前端框架，主要特性包括：\n\n1. **Composition API** - 提供更灵活的组件逻辑组织方式\n2. **更好的TypeScript支持** - 内置TS支持，提供更好的类型安全\n3. **性能优化** - 重构虚拟DOM，提升渲染性能\n4. **更小的包体积** - 通过Tree-shaking减少最终包大小\n5. **新的组件生命周期** - 更清晰的组件生命周期钩子\n\n您想了解哪个特性的更多细节吗？',
            created_at: new Date('2024-01-15T10:30:15').toISOString()
          }
        ],
        processing_tasks: [],
        result_panels: []
      },
      2: {
        id: 2,
        title: '深圳AQI趋势分析',
        created_at: new Date(Date.now() - 172800000).toISOString(),
        type: 'data',
        messages: [
          {
            id: 1,
            role: 'user',
            content: '最近一个月深圳市的AQI变化趋势，请帮我分析一下',
            created_at: new Date('2024-01-14T14:20:00').toISOString()
          },
          {
            id: 2,
            role: 'assistant',
            content: '根据最近一个月深圳市的AQI数据分析，我为您总结以下趋势：\n\n**总体趋势：**\n- AQI整体呈现下降趋势，空气质量逐步改善\n- 优良天数占比达到85%，较上月提升5个百分点\n- 轻度污染天数减少3天，中度污染天数减少1天\n\n**主要污染物：**\n- PM2.5仍然是主要污染物，占比45%\n- PM10占比25%，O3占比20%，其他污染物占比10%\n\n**建议措施：**\n1. 继续加强工业排放管控\n2. 优化交通流量管理\n3. 增加城市绿化覆盖率',
            created_at: new Date('2024-01-14T14:20:30').toISOString()
          }
        ],
        processing_tasks: [],
        result_panels: []
      }
    }
    
    return mockData[id] || mockData[1]
  } catch (error) {
    console.error(`Failed to get conversation detail for id ${id}:`, error)
    throw error
  }
}

// 创建新对话
export async function createConversation(data: CreateConversationRequest): Promise<Conversation> {
  try {
    // 如果有真实API，使用真实API
    // const response = await post<Conversation>('/conversations', data)
    // return response.data
    
    // 模拟创建对话
    const newConversation: Conversation = {
      id: Date.now(), // 模拟ID
      title: data.title,
      created_at: new Date().toISOString(),
      type: data.type
    }
    
    return newConversation
  } catch (error) {
    console.error('Failed to create conversation:', error)
    throw error
  }
}

// 删除对话
export async function deleteConversation(id: number): Promise<void> {
  try {
    // 如果有真实API，使用真实API
    // await del(`/conversations/${id}`)
    
    // 模拟删除
    console.log(`Deleting conversation ${id}`)
  } catch (error) {
    console.error(`Failed to delete conversation ${id}:`, error)
    throw error
  }
}